#include "BH1750.h"

/**
 * @brief 按默认参数初始化BH1750，连续高分辨率模式，1lx，120ms
 * @brief 读取时，需要延时120ms，使用BH1750_ReadData()函数
 *
 */
void BH1750_DefaultInit(void)
{
    BH1750_ON();
    BH1750_SetMode(BH1750_CON_H);
}

/**
 * @brief 开启BH1750
 *
 */
void BH1750_ON(void)
{
    i2c_start();
    i2c_write_byte(BH1750_SlaveAddress | 0); // Slave address,SA0=0, write
    i2c_wait_ack();
    i2c_write_byte(BH1750_UP); // ON command
    i2c_wait_ack();
    i2c_stop();
}

/**
 * @brief 关闭BH1750
 *
 */
void BH1750_OFF(void)
{
    i2c_start();
    i2c_write_byte(BH1750_SlaveAddress | 0); // Slave address,SA0=0, write
    i2c_wait_ack();
    i2c_write_byte(BS1750_DOWN); // OFF command
    i2c_wait_ack();
    i2c_stop();
}

void BH1750_Reset(void)
{
    i2c_start();
    i2c_write_byte(BH1750_SlaveAddress | 0); // Slave address,SA0=0, write
    i2c_wait_ack();
    i2c_write_byte(BH1750_RSET); // Reset command
    i2c_wait_ack();
    i2c_stop();
}

/**
 * @brief 设置BH1750的模式
 *
 * @param mode 模式，参考BH1750.h   注意不同模式下的延时
 */
void BH1750_SetMode(unsigned char mode)
{
    i2c_start();
    i2c_write_byte(BH1750_SlaveAddress | 0); // Slave address,SA0=0, write
    i2c_wait_ack();
    i2c_write_byte(mode); // Set mode command
    i2c_wait_ack();
    i2c_stop();
}

/**
 * @brief 读取BH1750的数据
 *
 * @return float 光照强度，单位lx
 */
float BH1750_ReadData(void)
{
    unsigned char BUF[2];
    unsigned short temp;
    i2c_start();
    i2c_write_byte(BH1750_SlaveAddress | 1); // Slave address,SA0=0
    i2c_wait_ack();
    BUF[0] = i2c_read_byte(1);
    BUF[1] = i2c_read_byte(0);
    i2c_stop();
    temp = BUF[0] << 8 | BUF[1];
    return (float)temp / 1.2;
}
